package com.wuwei.elearning.messageQueen;

import com.wuwei.elearning.dto.ConversionMessage;
import com.wuwei.elearning.enumPackage.Constant;
import com.wuwei.elearning.question.domain.Word;
import com.wuwei.elearning.question.mapper.PptMapper;
import com.wuwei.elearning.question.mapper.WordMapper;
import com.wuwei.elearning.service.CacheService;
import com.wuwei.elearning.utils.DocumentService;
import com.wuwei.elearning.utils.MinioUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.jodconverter.core.office.OfficeException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * A simple implementation of MessageConsumer
 */
@Slf4j
@Component
public class WordMessageConsumer implements MessageConsumer {
    private String topic = Constant.WORD_CONVERSION_TOPIC;

    @Resource
    private MinioUtil minioUtil;

    @Resource
    private DocumentService documentService;

    @Resource
    private CacheService cacheService;

    /**
     * Default constructor for Spring to use
     */
    public WordMessageConsumer() {
        // Default constructor for Spring
    }

    @Resource
    private WordMapper wordMapper;
    
    @Override
    public boolean consume(ConversionMessage conversionMessage) {
        Message message = (Message)conversionMessage.getPayload();
        try {
            String fileName = message.getFileName();
            Long pptId = message.getId();
            String minioPath = message.getMinioPath();

            log.info("接收到转换任务: {} - {}", fileName, System.currentTimeMillis());

            String url = "temp-pdf.pdf";
            File tempInputFile = new File("temp-input-" + fileName);
            File outputFile = new File(url);

            try {
                // 从MinIO下载文件到临时文件
                minioUtil.downloadFile(minioPath, tempInputFile);
                fileName = fileName.substring(0, fileName.lastIndexOf("."))+".pdf";
                // 转换文件
                try (FileInputStream inputStream = new FileInputStream(tempInputFile)) {
                    documentService.convertStreamToPdf(inputStream, outputFile);
                    String previewUrl = minioUtil.uploadPdf(outputFile, fileName);
                    String upload = Constant.PDF + "/" + fileName;
                    String redisKey = Constant.MINIO_PDF + upload;
                    cacheService.setEx(redisKey, previewUrl, 6, TimeUnit.DAYS);

                    Word word = wordMapper.selectById(pptId);
                    word.setUrl(upload);
                    wordMapper.updateById(word);

                    log.info("转换操作完成！-{}", System.currentTimeMillis());
                }
            } catch (IOException e) {
                throw new RuntimeException("处理转换任务失败", e);
            } finally {
                // 清理临时文件
                if (tempInputFile.exists()) {
                    tempInputFile.delete();
                }
                if (outputFile.exists()) {
                    outputFile.delete();
                }

                // 可选：删除MinIO中的临时文件
                minioUtil.remove(minioPath);
            }
        } catch (OfficeException e) {
            pptMapper.deleteById(message.getId());
            throw new RuntimeException("转换失败", e);
        }
        return true;
    }

    @Resource
    private PptMapper pptMapper;



    @Override
    public String getTopic() {
        return topic;
    }
} 